<template>
	<!-- template部分 -->
	<view class="form-item">
		<text class="label">商品分类</text>
		<picker mode="multiSelector" :value="multiIndex" :range="multiRange" range-key="name" @change="onCategoryChange" @columnchange="onColumnChange">
			<view class="picker-display">{{ multiRange[0][multiIndex[0]].name }} - {{ multiRange[1][multiIndex[1]].name }}</view>
		</picker>
	</view>
</template>

<script>
// script部分
export default {
	data() {
		return {
			// 所有分类数据，实际项目中应从服务器获取
			allCategories: [
				{ name: '家用电器', sub: [{ name: '冰箱' }, { name: '电视' }, { name: '洗衣机' }] },
				{ name: '数码产品', sub: [{ name: '手机' }, { name: '相机' }, { name: '耳机' }] },
				{ name: '图书音像', sub: [{ name: '小说' }, { name: '教材' }, { name: 'CD' }] }
			],
			multiIndex: [0, 0], // 选中的下标数组，[一级分类下标, 二级分类下标]
			multiRange: [] // picker的实际数据源
		};
	},
	created() {
		this.initPickerData();
	},
	methods: {
		initPickerData() {
			const firstCol = this.allCategories;
			const secondCol = this.allCategories[0].sub; // 默认的二级分类
			this.multiRange = [firstCol, secondCol];
		},

		onColumnChange(e) {
			console.log('滚动了第 ' + (e.detail.column + 1) + ' 列，选中了第 ' + (e.detail.value + 1) + ' 项');

			// 核心：只在滚动第一列时才更新第二列的数据
			if (e.detail.column === 0) {
				const newFirstIndex = e.detail.value;
				const newSecondCol = this.allCategories[newFirstIndex].sub;

				// 更新 multiIndex 的第一项
				this.$set(this.multiIndex, 0, newFirstIndex);
				// 重置第二列的选中项为第一个
				this.$set(this.multiIndex, 1, 0);

				// 更新 multiRange 的第二列数据
				this.$set(this.multiRange, 1, newSecondCol);
			}
		},

		onCategoryChange(e) {
			console.log('用户确认了分类选择：', e.detail.value);
			// 更新最终的选中值
			this.multiIndex = e.detail.value;
			const cat1 = this.multiRange[0][this.multiIndex[0]].name;
			const cat2 = this.multiRange[1][this.multiIndex[1]].name;
			console.log(`最终提交的分类是: ${cat1} / ${cat2}`);
		}
	}
};
</script>

<style scoped>
/* style部分 (与场景一完全相同) */
.form-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 15px;
	background-color: #ffffff;
	border-bottom: 1px solid #f0f0f0;
	font-size: 16px;
}
.label {
	color: #333333;
	flex-shrink: 0;
	margin-right: 15px;
}
.picker-display {
	display: flex;
	align-items: center;
	color: #888888;
	text-align: right;
	flex-grow: 1;
	justify-content: flex-end;
}
.arrow-icon {
	margin-left: 8px;
	color: #cccccc;
	font-weight: bold;
}
picker[disabled] .picker-display {
	color: #c0c0c0;
	cursor: not-allowed;
}
</style>
